/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
 *
 */

import { resolve } from 'path';

import { LocalFileWriter } from '../../../common/util/local-file-writer.js';
import { PathUtil } from '../../../common/util/path-util.js';
import { HvigorCoreNode } from '../../external/core/hvigor-core-node.js';
import { defaultModelRegistry } from '../../external/default-tooling-model-bean-registry.js';
import { HvigorLogger } from '../../log/hvigor-log.js';
import { DefaultSyncTask } from '../task/core/default-sync-task.js';

const _log = HvigorLogger.getLogger('hvigor-process');

/**
 * 执行每个module中注册的sync类型的任务，将对应的数据模型注册到registry中
 *
 * @param {HvigorCoreNode} hvigorNode
 */
export function findSyncTaskPathsForNode(hvigorNode: HvigorCoreNode): string[] {
  return hvigorNode
    .getAllTasks()
    .filter((value) => {
      // sync类型的任务才需要执行
      return value instanceof DefaultSyncTask;
    })
    .map((value) => {
      return value.getPath();
    });
}

/**
 * 打印sync的信息到输出流中
 */
export function outputPluginSyncInfo(): void {
  const output = Object.create(null);
  defaultModelRegistry.getModelMap().forEach((value, key) => (output[key] = value.buildModel()));
  output.version = 1;

  const syncOutputPath = resolve(PathUtil.getHvigorCacheDir(_log), 'outputs', 'sync', 'output.json');
  try {
    LocalFileWriter.getInstance().write(syncOutputPath, output);
  } catch (e) {
    _log.error('Sync info serialization failed.');
  }
}
